# -*- coding: utf-8 -*-
from flask import jsonify,current_app,Blueprint,json
import traceback
from functools import wraps
app = current_app

errorbp = Blueprint('error', __name__, url_prefix='/error')

def error_handle(func):
    @wraps(func)
    def inner(*args, **kwargs):
        try:
            print("error_________handle")
            return func(*args, **kwargs)
        except Exception as e:
            raise Myexception(e) from e
    return inner

class Myexception(Exception):
    def __init__(self, e):
        super(Exception, self).__init__()
        if isinstance(e,KeyError):
            self.message = '请求数据'+str(e)+'无效！'
            self.code = 400
        else:
            self.message = '服务器内部错误！'
            self.code = 500

    def to_dict(self):
        result ={
            "code":self.code,
            "msg":self.message,
        }
        return result

@errorbp.app_errorhandler(Myexception)
def handle_my_exception(error):
    print(traceback.format_exc())
    response = jsonify(error.to_dict())
    response.status_code = error.code
    return response
